#!/bin/bash

# ============================================
# Flutter Web 启动脚本 (macOS 通用版)
# ============================================

clear

echo ""
echo "========================================"
echo "   Flutter Web 启动工具 (macOS)"
echo "========================================"
echo ""

# 设置工作目录为脚本所在目录
cd "$(dirname "$0")" || exit 1

# ============================================
# 浏览器选择
# ============================================
echo "请选择浏览器："
echo "  1) Chrome (默认)"
echo "  2) Edge"
echo "  3) Safari"
echo "  4) Firefox"
echo ""
echo -n "输入序号 (3秒后自动选择 Chrome): "

# 读取用户输入，3秒超时
BROWSER_CHOICE=""
read -t 3 BROWSER_CHOICE 2>/dev/null

# 根据选择设置浏览器
case "$BROWSER_CHOICE" in
    2)
        BROWSER="edge"
        BROWSER_NAME="Edge"
        ;;
    3)
        BROWSER="safari"
        BROWSER_NAME="Safari"
        ;;
    4)
        BROWSER="firefox"
        BROWSER_NAME="Firefox"
        ;;
    *)
        BROWSER="chrome"
        BROWSER_NAME="Chrome"
        ;;
esac

echo ""
echo "✓ 已选择: $BROWSER_NAME"
echo ""

# ============================================
# 配置参数
# ============================================
WEB_PORT=8080
WEB_HOSTNAME=127.0.0.1

echo "========================================"
echo "  启动配置"
echo "========================================"
echo "浏览器: $BROWSER_NAME"
echo "端口: $WEB_PORT"
echo "主机: $WEB_HOSTNAME"
echo "访问地址: http://$WEB_HOSTNAME:$WEB_PORT"
echo "========================================"
echo ""

# ============================================
# 清理旧进程
# ============================================
echo "正在清理旧进程..."
pkill -f "dart.*flutter" 2>/dev/null
pkill -f "flutter.*run" 2>/dev/null
sleep 1
echo "✓ 进程清理完成"
echo ""

# ============================================
# 检查 Flutter
# ============================================
if ! command -v flutter &> /dev/null; then
    echo "❌ 错误: 未找到 Flutter！"
    echo "请先安装 Flutter 并添加到 PATH 环境变量"
    echo ""
    read -n 1 -s -r -p "按任意键退出..."
    exit 1
fi

echo "✓ Flutter 环境正常"
echo ""

# ============================================
# 启动应用
# ============================================
echo "========================================"
echo "  正在启动 Flutter Web 应用..."
echo "========================================"
echo ""
echo "提示："
echo "  - 按 R 键可热重载"
echo "  - 按 Q 键可退出"
echo "  - 按 Ctrl+C 可强制停止"
echo ""
echo "========================================"
echo ""

# 启动 Flutter Web
flutter run -d "$BROWSER" --web-port="$WEB_PORT" --web-hostname="$WEB_HOSTNAME"

# ============================================
# 退出处理
# ============================================
echo ""
echo "========================================"
echo "  应用已停止"
echo "========================================"
echo ""
read -n 1 -s -r -p "按任意键关闭窗口..."

